package cc.facesign.admin.controller;


import cc.facesign.admin.bean.DeptTree;
import cc.facesign.admin.bean.TblDept;
import cc.facesign.admin.bean.TblManageDept;
import cc.facesign.admin.bean.query.DeptQuery;
import cc.facesign.admin.bean.vo.DeptVo;
import cc.facesign.admin.bean.vo.UserVo;
import cc.facesign.admin.service.TblDeptService;
import cc.facesign.admin.service.TblManageDeptService;
import cc.facesign.admin.service.TblUserService;
import cc.facesign.admin.utils.PageUtils;
import cc.facesign.admin.utils.PowerUtils;
import cc.facesign.common.exception.FacesignException;
import cc.facesign.common.utils.bean.R;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author testjava
 * @since 2022-05-06
 */
@RestController
@RequestMapping("/admin/dept")
@Api(description = "部门查询")
public class TblDeptController {

    @Autowired
    private TblDeptService deptService;

    @Autowired
    private PowerUtils powerUtils;

    @Autowired
    private TblManageDeptService manageDeptService;

    @Autowired
    private TblUserService userService;



    @PreAuthorize("@ex.hasAuthorith('root:exe:query')")
    @ApiOperation("获取部门信息")
    @GetMapping("/getInfoById/{id}")
    public R getInfoById(@PathVariable String id) {
        if (!powerUtils.getCurrentChildDeptIdSet().contains(id)) {
            throw new FacesignException(R.ERROR, "权限异常");
        }

       DeptVo vo = deptService.getInfoById(id);
       return R.ok().data("data", vo);
    }


    @PreAuthorize("@ex.hasAuthorith('admin')")
    @ApiOperation("获取所有根部门")
    @GetMapping("/getRootList")
    public R getRootList() {
        if (!powerUtils.isAdmin()) throw new FacesignException(R.ERROR, "权限异常");

        List<TblDept> rootList = deptService.getRootList();
        return R.ok().data("data", rootList);
    }

    /**
     * 根据根部门id获取部门树
     * @param id 部门id
     * @return cc.facesign.admin.bean.DeptTree
     */
    @PreAuthorize("@ex.hasAuthorith('root:exe:query')")
    @ApiOperation("根据部门id获取子部门树")
    @GetMapping("/getTree/{id}")
    public R getTree(@PathVariable String id) {
        if (!powerUtils.getCurrentChildDeptIdSet().contains(id)) {
            throw new FacesignException(R.ERROR, "权限异常");
        }

        DeptTree tree = deptService.getTreeByDeptId(id);
        return R.ok().data("data", Collections.singletonList(tree));
    }


    /**
     * 查部门信息列表【条件+分页】
     * @param current 当前页
     * @param limit 每页数量
     * @param query 查询vo
     * @return
     */
    @PreAuthorize("@ex.hasAuthorith('root:exe:query')")
    @ApiOperation("查部门信息列表【条件+分页】")
    @PostMapping("/getByPageCondition/{current}/{limit}")
    public R getByPageCondition(@PathVariable("current") Integer current,
                                @PathVariable("limit") Integer limit,
                                @RequestBody DeptQuery query) {
        String id = query.getId();
        String name = query.getName();
        String pid = query.getPid();
        String status = query.getStatus();
        String rid = query.getRid();

        if (!StringUtils.isEmpty(pid) && !powerUtils.getCurrentChildDeptIdSet().contains(pid) ||
                !StringUtils.isEmpty(rid) && !powerUtils.isAdmin()) {
            throw new FacesignException(R.ERROR, "权限异常");
        }

        QueryWrapper<TblDept> w = new QueryWrapper<>();
        if (!StringUtils.isEmpty(id)) w.eq("id", id);
        if (!StringUtils.isEmpty(name)) w.eq("name", name);
        if (!StringUtils.isEmpty(pid)) w.eq("pid", pid);
        if (!StringUtils.isEmpty(status)) w.eq("status", status);
        if (!StringUtils.isEmpty(rid)) w.eq("rid", rid);

        List<String> list = deptService.list(w).stream()
                .map(TblDept::getId)
                .collect(Collectors.toList());
        List<DeptVo> res = deptService.getInfoBatch(list);

        IPage<DeptVo> page = PageUtils.page(res, current, limit);
        return R.ok().data("page", page);
    }

    /**
     * 单位不同并不能查看
     * @param deptId 部门id
     * @return 用户信息
     */
    @PreAuthorize("@ex.hasAuthorith('root:exe:query')")
    @ApiOperation("获取部门管理员列表")
    @GetMapping("/getManager/{deptId}")
    public R getManager(@PathVariable String deptId) {
        if (!powerUtils.getCurrentChildDeptIdSet().contains(deptId)) {
            throw new FacesignException(R.ERROR, "权限异常");
        }

        QueryWrapper<TblManageDept> w = new QueryWrapper<>();
        w.eq("dept_id", deptId);
        List<String> userIds = manageDeptService.list(w).stream()
                .map(x -> x.getUserId())
                .collect(Collectors.toList());

        List<UserVo> res = userService.getInfoByIdBatch(userIds);

        return R.ok().data("data", res);
    }

}

